﻿var fieldData;
var selectedFieldObj;
var uploadStatusText = "Uploading";
var fileFormatErrorText = "File format error";

$(document).ready(function () {

    fieldData = new Object();
    $('#field-type-content').dialog({
        autoOpen: false,
        modal: true,
        buttons: {
            Cancel: function () {
                $(this).dialog('close');
            },
            OK: function () {
                var fld = addField($('#field-type option:selected').val());
                createTextElForField(fld);
                createImgElForField(fld);
                setSelected(fld);
                $(this).dialog('close');
            }
        }
    });

    $('#create-field').click(function () {
        $('#field-type-content').dialog('open');

    });
    initPropertiesChangeHandlers();
    $('#font-color').ColorPicker({ onSubmit: function (hsb, hex, rgb, el) {
        $(el).val($(el).val().substr(0, 2) + hex);
        $(el).blur();
        $(el).ColorPickerHide();
    }
    });
    $('#save-template-link').click(function () {

        $('#template-json').val(JSON.stringify(convertToPointUnits()));
        $(this).parents('form').submit();
    });


    var button = $('#upload-button'), interval;
    new AjaxUpload(button, {
        action: '/AdminPanel/Template/HandleBackgroundImg',
        name: 'myfile',
        responseType: 'json',
        onSubmit: function (file, ext) {
            var uploadStatus = $('#file-upload-status');
            if (ext && /^(jpg|jpeg|png)$/.test(ext.toLowerCase())) {
                $('#customizationZone #productImg').remove();
                uploadStatus.html(uploadStatusText);
                uploadStatus.fadeIn();
            } else {
                uploadStatus.html(fileFormatErrorText);
                uploadStatus.fadeIn();
                return false;
            }

            // If you want to allow uploading only 1 file at time,
            // you can disable upload button
            this.disable();

            interval = window.setInterval(function () {
                var text = uploadStatus.html();
                if (text.length < 13) {
                    uploadStatus.html(text + '.');
                } else {
                    uploadStatus.html(uploadStatusText);
                }
            }, 200);
        },
        onComplete: function (file, response) {
            if (response.Valid) {
                var imgEl = $('<img/>').attr('src', response.FilePath)
                                       .attr('alt', 'product-image')
                                       .attr('id', 'productImg');
                $('#customizationZone').append(imgEl);
                $('#file-upload-status').fadeOut();
            }
            else {
                $('#file-upload-status').html(fileFormatErrorText);
            }
            window.clearInterval(interval);
            this.enable();
        }
    });

});

function convertToPointUnits() {
    var resData = new Object();
    resData.Items = new Array();
    resData.Width = $("#productImg").width() / 2;
    resData.Height = $("#productImg").height() / 2;
    
    var idx = 0;
    $.each(fieldData, function (data) {

        var fEl = fieldData[data];
        if (fEl != null) {
            //Setting Y coordinate value from bottom line
            fEl.Align.Y = fEl.Align.Y + $('#' + fEl.FieldName + 'Img').height();

            fEl.Align.X = (fEl.Align.X / $("#productImg").width()) * $("#productImg").width() / 2;
            fEl.Align.Y = (1 - fEl.Align.Y / $("#productImg").height()) * $("#productImg").height() / 2;
            resData.Items[idx] = fEl;
            idx++;
        }
    });
    return resData;
}

//Converts Points to pixels for positioning
function normalizeTextItem(item, jsData) {
    var widthInPoints = jsData.Width;
    var heightInPoints = jsData.Height;

    item.Align.X = (item.Align.X / widthInPoints) * $("#productImg").width();
    item.Align.Y = (1 - item.Align.Y / heightInPoints) * $("#productImg").height();
    //item.Size = item.Size;// * 1.7;
}

function setSelected(fieldObj) {
    var imgSelector;
    if (selectedFieldObj != null) {
         imgSelector = "#" + selectedFieldObj.FieldName + "Img";
         $(imgSelector).removeClass('selected-text');
         $('#' + selectedFieldObj.FieldName + '-cont').removeClass('selected-field');
    }
    selectedFieldObj = fieldObj;
    initPropertiesPanel(selectedFieldObj);
    imgSelector = '#' + fieldObj.FieldName + 'Img';
    $(imgSelector).addClass('selected-text');
    $('#' + selectedFieldObj.FieldName + '-cont').addClass('selected-field');

}

function createTextElForField(fieldObj) {

    var texElCont = $('<div/>').attr('id', fieldObj.FieldName + '-cont');
    var textEl = $('<input/>').attr('type', 'text').attr('id', fieldObj.FieldName);
    textEl.val(fieldObj.Text);
    var labelEl = $('<label/>').attr('id',fieldObj.FieldName +'-label');
    labelEl.html(fieldObj.FieldName);

    var deleteLink = $('<a/>').attr('id', fieldObj.FieldName + '-delete')
                              .attr('rel', fieldObj.FieldName)
                              .attr('href', 'javascript:void');

    deleteLink.click(function () {
        texElCont.remove();
        $('#' + fieldObj.FieldName + 'Img').remove();
        fieldData[fieldObj.FieldName] = null;
        if (selectedFieldObj == fieldObj) {
            selectedFieldObj = null;
        }
    });
    deleteLink.html('delete');

    texElCont.append(labelEl);
    texElCont.append(textEl);
    texElCont.append(deleteLink);

    $('#template-fields').append(texElCont);
    
    textEl.keyup(function () {
            var textVal = $.trim($(this).val());
            var obj = fieldData[$(this).attr('id')];
            obj.Text = textVal;
            var imgSelector = "#" + $(this).attr('id') + "Img";
            applyDataToImage(obj, $(imgSelector), false);
        });

        textEl.click(function () {
            setSelected(fieldObj);
        });
}

function initPropertiesChangeHandlers() {
    $('#text-pos-y').keyup(function () {
        selectedFieldObj.Align.Y = $(this).val();
        var imgSelector = "#" + selectedFieldObj.FieldName + "Img";
        alignTextFieldImg(selectedFieldObj, $(imgSelector));
    });

    $('#text-pos-x').keyup(function () {
        selectedFieldObj.Align.X = $(this).val();
        var imgSelector = "#" + selectedFieldObj.FieldName + "Img";
        alignTextFieldImg(selectedFieldObj, $(imgSelector));
    });

    $('#text-max-lenght').keyup(function () {
        selectedFieldObj.MaxLength = $(this).val();
    });

    $('#font-color').blur(function () {
        selectedFieldObj.Color = $(this).val();
        var imgSelector = "#" + selectedFieldObj.FieldName + "Img";
        applyDataToImage(selectedFieldObj, $(imgSelector),false);
    });

    $('#font-size').blur(function () {
        selectedFieldObj.Size = $(this).val();
        var imgSelector = "#" + selectedFieldObj.FieldName + "Img";
        applyDataToImage(selectedFieldObj, $(imgSelector), false);
    });

    $('select#font-align').change(function () {
        selectedFieldObj.Align.GrowTo = $('select#font-align option:selected').val();
        var imgSelector = "#" + selectedFieldObj.FieldName + "Img";
        selectedFieldObj.Align.Halign = 'abs';
        $('select#font-position').val('abs');
        alignTextFieldImg(selectedFieldObj, $(imgSelector));
    });

    $('select#font-position').change(function () {
        selectedFieldObj.Align.Halign = $('select#font-position option:selected').val();
        var imgSelector = "#" + selectedFieldObj.FieldName + "Img";
        alignTextFieldImg(selectedFieldObj, $(imgSelector));
    });

    
}

function initPropertiesPanel(fieldObj) {
    $('select#font-select').val(fieldObj.FontId);
    $('#font-size').val(fieldObj.Size);

    $('#font-color').val(fieldObj.Color);

    $('#text-pos-x').val(fieldObj.Align.X);
    $('#text-pos-y').val(fieldObj.Align.Y);
    $('#text-max-lenght').val(fieldObj.MaxLength);
    $('select#font-align').val(fieldObj.Align.GrowTo);
    $('select#font-position').val(fieldObj.Align.Halign);
}

function createImgElForField(fieldObj) {

    var imgId = fieldObj.FieldName + 'Img';
    //normalizeTextItem(fieldObj, data);
    var imgEl = $('<img/>').attr('id', imgId).attr('alt', fieldObj.FieldName);
    imgEl.mousedown(function () {
        setSelected(fieldObj);
    });
    
    //imgEl.addClass('selected-text');
    imgEl.draggable({ containment: 'parent', drag: function (event, ui) {
        // var obj = fieldData[$(this).attr('alt')];

        if (fieldObj.Align.GrowTo == 'left') {
            var xCord = parseInt(ui.position.left) + imgEl.width();
            fieldObj.Align.X = xCord;
        } else {
            fieldObj.Align.X = parseInt(ui.position.left);
        }
        fieldObj.Align.Y = parseInt(ui.position.top);
        initPropertiesPanel(fieldObj);
    }
    });
    imgEl.css({ position: 'absolute' });
    $('#customizationZone').append(imgEl);
    imgEl.hide();
    
    applyDataToImage(fieldObj, imgEl, true);
}

function addField(name) {
    var fieldObj = new Object();

    fieldObj.FieldName = name;
    fieldObj.Text = 'Text here';
    fieldObj.FontId = 1;
    fieldObj.Size = 12;
    fieldObj.Color = 'FF000000';
    fieldObj.MaxLength = 20;

    fieldObj.Align = new Object();
    fieldObj.Align.X = 20;
    fieldObj.Align.Y = 20;
    fieldObj.Align.Halign = 'abs';
    fieldObj.Align.GrowTo = 'right';

    fieldData[name] = fieldObj;
    return fieldObj;
}


function alignTextFieldImg(fieldObj, imageObj) {
    var yCord = fieldObj.Align.Y; // - imageObj.height();
    if (fieldObj.Align.Halign == 'abs') {
        if (fieldObj.Align.GrowTo == 'right') {
            imageObj.css({ left: fieldObj.Align.X + "px", top: yCord + "px" });

        }
        else if (fieldObj.Align.GrowTo == 'left') {
            var xCord = fieldObj.Align.X - imageObj.width();
            imageObj.css({ left: xCord + "px", top: yCord + "px" });
        }
    }
    else if (fieldObj.Align.Halign == 'center') {
        var xCord = $("#productImg").width() / 2 - imageObj.width() / 2;
        imageObj.css({ left: xCord + "px", top: yCord + "px" });
    }
}

function applyDataToImage(data, imageObj, fade) {

    imageObj.attr('src', '/en/ImageFromText/' +
                                data.FontId + '/' +
                                data.Color + '/' +
                                data.Size + '?text=' + encodeURIComponent(data.Text));

    //Align images after loading only for correct width
    imageObj.load(function () {
        if (!fade) {
            imageObj.show();
        }
        alignTextFieldImg(data, imageObj);
        if (fade) {
            imageObj.fadeIn("slow");
        }
    })
        .error(function () { $(this).hide() });
}